#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/5 13:20
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : Oauth2PasswordBearer.py
# @Software: PyCharm
# @FileDescription：重构权限校验
from typing import Optional

from fastapi.security import OAuth2PasswordBearer
from fastapi.security.utils import get_authorization_scheme_param
from starlette.status import HTTP_401_UNAUTHORIZED
from fastapi import Request, HTTPException

from core.config import settings


class OAuth2Password(OAuth2PasswordBearer):
    async def __call__(self, request: Request) -> Optional[str]:
        authorization: str = request.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if not authorization or scheme.lower() != settings.TOKEN_HEAD.lower():
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="用户过期，请重新登陆",
                    headers={"WWW-Authenticate": settings.TOKEN_HEAD},
                )
            else:
                return None
        return param
